package com.ms.content.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ms.common.utils.R;
import com.ms.content.controller.AdmsController;
import com.ms.content.dao.MiaoshaActivityDao;
import com.ms.content.entity.AdmsEntity;
import com.ms.content.entity.GoodsEntity;
import com.ms.content.entity.MiaoshaActivityEntity;
import com.ms.content.service.AdmsService;
import com.ms.content.service.GoodsService;
import com.ms.content.service.MiaoshaActivityService;
import com.ms.content.util.SnowflakeIdWorker;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ms.common.utils.PageUtils;
import com.ms.common.utils.Query;

import com.ms.content.dao.OrderInfoDao;
import com.ms.content.entity.OrderInfoEntity;
import com.ms.content.service.OrderInfoService;


@Service("orderInfoService")
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoDao, OrderInfoEntity> implements OrderInfoService {

    @Autowired
    private GoodsService goodsService;


    @Autowired
    private MiaoshaActivityDao miaoshaActivityDao;

    @Autowired
    private OrderInfoDao orderInfoDao;


    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private RedissonClient redissonClient;


    @Autowired
    private AdmsService admsService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<OrderInfoEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", params.get("uid"));
        IPage<OrderInfoEntity> page = this.page(
                new Query<OrderInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void insert(Integer fid, Integer id, String uid, Integer sid) {
        OrderInfoEntity orderInfoEntity = new OrderInfoEntity();
        System.out.println(fid + id + uid);
        GoodsEntity goodsEntity = goodsService.seleByIdsj(sid);
        System.out.println("商品表" + goodsEntity);
        AdmsEntity abms = admsService.infoxx(id);
        System.out.println("中间表" + abms);
        //商品选择秒杀库存的数量  在商品表中去减去
        goodsEntity.setGoodsStock(goodsEntity.getGoodsStock() - 1);
        abms.setMsCount(abms.getMsCount() - 1);

       admsService.updateById(abms);
        //库存正常减1  正常创建订单
//        if (b) {
            goodsService.updateById(goodsEntity);
            System.out.println(goodsEntity);
            System.out.println(orderInfoEntity);
            BeanUtils.copyProperties(goodsEntity, orderInfoEntity);
            System.out.println(orderInfoEntity);
            orderInfoEntity.setCreateDate(new Date());
            orderInfoEntity.setUserId(uid);
            orderInfoEntity.setGoodsId(goodsEntity.getId());
            //
            String s = UUID.randomUUID().toString();
            System.out.println(s);
            orderInfoEntity.setId(s);
            orderInfoEntity.setGooId(Long.valueOf(fid));
            orderInfoEntity.setGoodsPrice(abms.getMsPrice());
            orderInfoEntity.setGoodsCount(1);
            System.out.println(orderInfoEntity);
            baseMapper.save(orderInfoEntity);
//            if (insert>0){
//                String ss = stringRedisTemplate.opsForValue().get(id + "");
//                stringRedisTemplate.opsForValue().set(id + "", String.valueOf(Integer.parseInt(ss) - 1));
//            }
            System.out.println("添加订单表");
//        }
    }

    @Override
    public void alipayNotify(Map<String, String> maps) {

    }

    @Override
    public OrderInfoEntity getByIdbu(String id) {
        QueryWrapper<OrderInfoEntity> id1 = new QueryWrapper<OrderInfoEntity>().eq("id", id);
        OrderInfoEntity orderInfoEntity = baseMapper.selectOne(id1);
        return orderInfoEntity;
    }

    @Override
    public R ms(Integer fid, Integer id, String uid, Integer sid,String path) throws InterruptedException {
        System.out.println("fid: "+fid+"id: "+id+"uid: "+uid+"sid: "+sid);
        String s1 = stringRedisTemplate.opsForValue().get("miaosha" + sid);
//        int s2 = Integer.parseInt(stringRedisTemplate.opsForValue().get(uid+"uid"));
//        System.out.println(s2);
//        if (s2==0){
//            return R.error("用户已经提交5此了");
//        }
        if (!path.equals(s1)) {
            return R.error("地址错误");
        }
        //获取读写锁
        RReadWriteLock cateRWlock = redissonClient.getReadWriteLock("cateRWlock");
        //获取写锁
        RLock writeLock = cateRWlock.writeLock();
        //尝试获取锁
        boolean lock = writeLock.tryLock(1, TimeUnit.MINUTES);
        if (lock) {//获取锁成功
            try {
                //活动fid   商品id  这个方法是根据设计秒杀活动时每用户最多购买  指定购买量设定的
//                    List<OrderInfoEntity> w = baseMapper.selectList(new QueryWrapper<OrderInfoEntity>().eq("user_id",uid));
//                    MiaoshaActivityEntity m = miaoshaActivityDao.selectOne(new QueryWrapper<MiaoshaActivityEntity>().eq("id",fid));
//                    if (m.getXg()!=0 && w.size()==m.getXg()){
//                        System.out.println("每个用户限购"+m.getXg()+"次   "+new Date());
//                        return R.error("每个用户限购"+m.getXg()+"次");
//                    }
//                  redis中缓存数量 -1


                String s = stringRedisTemplate.opsForValue().get("count");
                List<HashMap<Integer, Integer>> hashMaps = JSON.parseObject(s, new TypeReference<List<HashMap<Integer, Integer>>>() {
                });
                for (HashMap<Integer, Integer> hashMap : hashMaps) {
                    Integer integer = hashMap.get(id);
                    if (integer!=null){
                        if (integer <= 0){
                            System.out.println("该商品已被秒杀完   " + new Date());
                            return R.error("该商品已秒杀完");
                        }else{
                            hashMap.put(id,integer-1);
                            System.out.println(hashMap);
                            break;
                        }
                    }
                }
                System.out.println(hashMaps);
                stringRedisTemplate.opsForValue().set("count",JSON.toJSONString(hashMaps));
//                System.out.println("订单" + "的数量:" + s);
//                if (Integer.parseInt(s) <= 0) {
//                    System.out.println("该商品已被秒杀完   " + new Date());
//                    return R.error("该商品已秒杀完");
//                }
                //取list  看是否包含sid
                String listsid = stringRedisTemplate.opsForValue().get(uid + "");
                if (listsid==null){
                    List<String> strings1 = new ArrayList<>();
                    strings1.add(fid+","+sid);
                    stringRedisTemplate.opsForValue().set(uid,JSON.toJSONString(strings1),30,TimeUnit.MINUTES);
                }else{
                    //原来的字符串转化为集合
                    List<String> strings = JSON.parseObject(listsid, new TypeReference<List<String>>() {
                    });
                    Integer i = 0;
                    for (String string : strings) {
                        String[] split = string.split(",");
                        System.out.println(split[0]);
                        System.out.println(split[1]);
                        if (split[1].equals(String.valueOf(sid)) && split[0].equals(String.valueOf(fid))){
                            i=1;
                        }
                    }
                    if (i.equals(1)){
                        return R.error("用户名购买重复");
                    }else{
                        strings.add(fid+","+sid);
                    }
                    String jsonString = JSON.toJSONString(strings);
                    System.out.println(jsonString+"加上商品id");
                    stringRedisTemplate.opsForValue().set(uid,jsonString,30,TimeUnit.MINUTES);
                }

                stringRedisTemplate.delete("goodsList1");

                //创建订单  使用rabbitmq异步生成  并且减
                  rabbitTemplate.convertAndSend("orderinfo", fid + "," + id + "," + uid + "," + sid);
               // orderInfoService.insert(fid,id,uid,sid);
                //添加订单表
//                try {
//                   orderInfoService.insert(fid,id,uid,sid);
//                } catch (Exception e) {
//                    return R.error("每人限购一次");
//                }

                //存用户  一个用户购买的商品数
//                HashMap<String,String> map = new HashMap<>();
//                List<HashMap<String, String>> hashMaps = new ArrayList<>();
//                redisTemplate.opsForHash().putAll(uid+"",map);

                //  orderInfoService.insert(fid,id,uid,sid);
                System.out.println("秒杀该商品成功   " + new Date());
                System.out.println("查到" + id);
                return R.ok();
            } finally {
                //删除锁
                writeLock.unlock();
            }
        } else {
            //获取锁失败 自旋等待 100ms 调用方法本身
//            try {
//                Thread.sleep(100);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            Thread.sleep(100);
            return ms(fid, id, uid, sid,path);
        }
    }

}